package com.example.myapplication;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.material.textfield.TextInputEditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private TextInputEditText editText;
    private TextView resultView;
    private TextView logView;
    private final OkHttpClient client = new OkHttpClient();

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        // 初始化视图
        editText = findViewById(R.id.text_input_edit_text); // 需要确认EditText的id
        resultView = findViewById(R.id.resultView);
        Button submitButton = findViewById(R.id.submitButton);

        // 设置按钮点击监听
        submitButton.setOnClickListener(v -> sendPostRequest());

        // 保持原有的边距处理
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        // 初始化日志视图
        logView = findViewById(R.id.logView);
        logView.setMovementMethod(new ScrollingMovementMethod());
    }
    private void appendLog(String newLog) {
        runOnUiThread(() -> {
            // 保持最多200行日志
            String[] lines = logView.getText().toString().split("\n");
            if (lines.length > 200) {
                StringBuilder sb = new StringBuilder();
                for (int i = 100; i < lines.length; i++) {
                    sb.append(lines[i]).append("\n");
                }
                logView.setText(sb.toString());
            }

            // 添加新日志并滚动到底部
            logView.append(newLog + "\n");
            final int scrollAmount = logView.getLayout().getLineTop(logView.getLineCount()) - logView.getHeight();
            if (scrollAmount > 0)
                logView.scrollTo(0, scrollAmount);
            else
                logView.scrollTo(0, 0);
        });
    }
    private void sendPostRequest() {
        String content = editText.getText().toString().trim();
        if (content.isEmpty()) {
            Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建JSON请求体
        JSONObject json = new JSONObject();
        try {
            json.put("content", content);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(json.toString(), JSON);

        // 创建请求
        Request request = new Request.Builder()
//                .url("http://10.0.2.2:5000/query") // 模拟器使用这个地址
//                .url("http://localhost:5000/query") // 模拟器使用这个地址
                .url("http://192.168.0.104:5000/query") // 个人pc的地址
                .post(requestBody)
                .build();

        // 异步执行请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() ->
                        Toast.makeText(MainActivity.this, "请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show()
                );
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    try {
                        JSONObject jsonResponse = new JSONObject(responseData);
                        String answer = jsonResponse.getString("answer");
                        String startupLogs = jsonResponse.getString("startup_logs");
                        runOnUiThread(() -> {
                            resultView.setText(answer);
                            resultView.setVisibility(View.VISIBLE);
                        });
                        appendLog("=== [ AI洁客执行情况 ] ===\n" + startupLogs);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        runOnUiThread(() ->
                                Toast.makeText(MainActivity.this, "数据解析失败", Toast.LENGTH_SHORT).show()
                        );
                    }
                } else {
                    runOnUiThread(() ->
                            Toast.makeText(MainActivity.this, "服务器错误: " + response.code(), Toast.LENGTH_SHORT).show()
                    );
                }
            }
        });
    }
}